package com.cuitrip.business.tripservice;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cuitrip.apiservice.TripBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.tripservice.model.CategoryInfo;
import com.cuitrip.component.flowlayout.TagView;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.FlowLayout;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.Utils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * 修改标签
 * Created  ak
 */
public class EditTripTagsActivity extends CustomUiFragmentActivity implements IProxyCallback {

    public static final String TAG_KEY = "trip_tag_key";
    public static final String PARENCATEID = "0";
    public static final int MAX_TAG_SIZE = 4;
    public ArrayList<CategoryInfo> tempTags = new ArrayList<>();
    @Bind(R.id.progress_bar)
    protected ProgressBar mLoadingProgress;
    protected View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CategoryInfo tag = (CategoryInfo) v.getTag();
            if (v.isSelected()) {
                LogHelper.e("omg", "deselect " + tag);
                tempTags.remove(tag);
                v.setSelected(false);
            } else {
                if (tempTags.size() >= MAX_TAG_SIZE) {
                    MessageUtils.showToast(getString(R.string.trip_attribute_tag_limit, 4));
                    return;
                }
                LogHelper.e("omg", "select " + tag);
                v.setSelected(true);
                tempTags.add(tag);
            }
        }
    };
    @Bind(R.id.select_tag_text)
    TextView selectTagText;
    @Bind(R.id.lv_category)
    ListView mCategoryList;
    @Bind(R.id.state_layout)
    StateLayout mStateLayout;
    private ArrayList<List<CategoryInfo>> catesList = new ArrayList<>();
    private ArrayList<CategoryInfo> selectedCateList = new ArrayList<>();
    private ApiProxy mApiProxy = new ApiProxy(this);
    private MyCategoryAdapter mAdapter;
    private ArrayList<CategoryInfo> parentCatesList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getIntent().hasExtra(TAG_KEY)) {
            List<CategoryInfo> categoryInfoList = getIntent().getParcelableArrayListExtra(TAG_KEY);
            selectedCateList.addAll(categoryInfoList);
        }
        super.onCreate(savedInstanceState, R.layout.activity_tag_create);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        selectTagText.setText(getString(R.string.trip_attribute_tag_limit, 4));

    }

    @Override
    public void initData() {
        mStateLayout.changeState(StateLayout.State.Loading);
        //showLoading();
        revertTags();
        fetchTags();
    }

    @Override
    public void initListener() {
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                initData();
            }
        });
    }

    public void revertTags() {
        tempTags.clear();
        tempTags.addAll(selectedCateList);
    }

    public void fetchTags() {
        TripBusiness.getTripCates(mApiProxy, PARENCATEID);
    }

    private void inflateTags() {
        mLoadingProgress.setVisibility(View.GONE);
        //mTagLayout.setVisibility(View.VISIBLE);
    }

    private TextView initTagItem(final CategoryInfo tag) {
        TagView textView = new TagView(EditTripTagsActivity.this
                , tag.getName());
        textView.setTag(tag);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
        textView.setBackgroundResource(R.drawable.selector_checkable_blue_corner);
        textView.setTextColor(getResources().getColorStateList(R.color.ct_white_qiaomai));
        textView.setOnClickListener(onClickListener);
        return textView;
    }

    protected void saveTags() {
        selectedCateList = tempTags;
    }

    private void saveAction() {
        saveTags();
        Intent intent = new Intent();
        intent.putExtra(TAG_KEY, selectedCateList);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        saveAction();
    }

    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.category);
        config.mTopbarRightAreaName = getString(R.string.operation_save);
        config.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public void onTopbarRightPress() {
        saveAction();
        finish();
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (response != null && response.code == CtResponseCode.RESULT_OK) {
            if (ApiManager.GET_TRIP_CATES.equals(response.getApiName())) {
                if (response.result instanceof List) {
                    LinkedHashMap<String, List> map = new LinkedHashMap<String, List>();
                    String secRequestCateIds = "";
                    List<CategoryInfo> categoryInfoList = (List<CategoryInfo>) response.result;
                    for (int i = 0; i < categoryInfoList.size(); ++i) {
                        String parent = categoryInfoList.get(i).getParent();
//                        String name = categoryInfoList.get(i).getName();
                        CategoryInfo categoryInfo = categoryInfoList.get(i);
                        if (PARENCATEID.equals(parent)) {
                            //第一级目录
                            parentCatesList.add(categoryInfo);
                            if (!TextUtils.isEmpty(secRequestCateIds)) {
                                secRequestCateIds += ",";
                            }
                            secRequestCateIds += categoryInfoList.get(i).getCategory();

                        } else {
                            //次级目录
                            //map.clear();
                            if (!map.containsKey(parent)) {
                                List<CategoryInfo> items = new ArrayList<CategoryInfo>();
                                items.add(categoryInfo);
                                map.put(parent, items);
                            } else {
                                map.get(parent).add(categoryInfo);
                            }
                        }
                    }
                    if (!TextUtils.isEmpty(secRequestCateIds)) {
                        TripBusiness.getTripCates(mApiProxy, secRequestCateIds);
                    }
                    if (map != null) {
                        for (String key : map.keySet()) {
                            List<CategoryInfo> list = map.get(key);
                            catesList.add(list);
                        }
                    }
                    mAdapter = new MyCategoryAdapter(parentCatesList);
                    mCategoryList.setAdapter(mAdapter);
                    mStateLayout.changeState(StateLayout.State.INIT);
                    //hideLoading();
                }
            }
        } else {
            // hideLoading();
            mStateLayout.changeState(StateLayout.State.NoNetwork);
            if (!TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
        }
        return false;
    }

    static class ViewHolder {
        TextView categoryText;
        FlowLayout categoryFlow;
    }

    private class MyCategoryAdapter extends BaseAdapter {
        private List<CategoryInfo> items;

        public MyCategoryAdapter(List<CategoryInfo> items) {
            this.items = items;
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_listview_edit_tags_activity, parent, false);
            holder = new ViewHolder();
            holder.categoryText = (TextView) convertView.findViewById(R.id.tv_category);
            holder.categoryFlow = (FlowLayout) convertView.findViewById(R.id.fl_category);
            if (parentCatesList != null) {
                holder.categoryText.setText(parentCatesList.get(position).getName());
            }
            holder.categoryFlow.setVerticalSpacing(Utils.dp2pixel(16));
            holder.categoryFlow.setHorizontalSpacing(Utils.dp2pixel(8));
            if (catesList != null && position < catesList.size()) {
                //获取子类别的list
                List<CategoryInfo> categoryItems = catesList.get(position);
                if (categoryItems != null) {
                    for (int i = 0; i < categoryItems.size(); i++) {
                        CategoryInfo tag = categoryItems.get(i);
                        TextView categoryItem = initTagItem(tag);
                        holder.categoryFlow.addView(categoryItem);
                        categoryItem.setSelected(tempTags.contains(tag));
                    }
                }
            }

            return convertView;
        }
    }
}
